package com.xgp.microChat.dev;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class BatTool {

    @Value("${xgp.myRedis.redisPath}")
    private String redisPath;
//    static String redisPath = "D:\\develop\\java\\Redis-x64-3.0.504\\redis-server.exe";
    @Value("${xgp.myMongodb.mongodbPath}")
    private String mongodbPath;
//static String mongodbPath = "D:\\develop\\java\\mongodb\\bin\\start.bat";

//    public static void main(String[] args) {
//        startCmd(redisPath);
//        System.out.println("redis已经打开了！");
//        startCmd(mongodbPath);
//        System.out.println("mongodb已经打开了！");
//    }

//    @Test
    public void openRedis() {
        startCmd(redisPath);
    }

//    @Test
    public void openMongoDb() {

        startCmd(mongodbPath);
    }

    public static void startCmd(String url) {
        // TODO Auto-generated method stub
        String batPath = url; // 把你的bat脚本路径写在这里
        File batFile = new File(batPath);
        boolean batFileExist = batFile.exists();
        System.out.println("batFileExist:" + batFileExist);
        if (batFileExist) {
            callCmd(batPath);
        }
    }

    private static void  callCmd(String locationCmd){
        StringBuilder sb = new StringBuilder();
        try {
            Process child = Runtime.getRuntime().exec("cmd /k start " + locationCmd);
            InputStream in = child.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
            String line;
            while((line=bufferedReader.readLine())!=null)
            {
                sb.append(line + "\n");
            }
            in.close();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println("sb:" + sb.toString());
            System.out.println("callCmd execute finished");
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
